<template>
    <div>
        <div class="demo-upload-list" v-for="(item, index) in uploadList">
            <template v-if="item.status === 'finished'">
                <img :src="ajaxUrl + '/' + item.url">
                <div class="demo-upload-list-cover">
                    <Icon type="ios-eye-outline" @click.native="handleView(item.url)"></Icon>
                    <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                </div>
            </template>
            <template v-else>
                <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
            </template>
        </div>

        <div class="ivu-upload" style="display: inline-block; width: 58px;" @click="uploadImg">
            <div class="ivu-upload ivu-upload-drag">
                <input type="file" class="ivu-upload-input" ref="input_file" @change="changeInputFile">
                <div style="width: 58px; height: 58px; line-height: 58px;">
                    <i class="ivu-icon ivu-icon-camera" style="font-size: 20px;"></i>
                </div>
            </div>
        </div>
        <Modal title="图片预览" v-model="visible" class-name="ivu-modal-wrap-custom" :styles="{'width': '700px'}">
            <img :src="imgUrl" style="width: 100%; height: 100%">
            <div slot="footer"></div>
        </Modal>
    </div>
</template>
<script>
    import util from '../../../libs/util';
    import qs from 'qs';
    export default {
        props: ['imgList'],
        data () {
            return {
                ajaxUrl: util.ajaxUrl,
                imgName: '',
                imgUrl: '',
                visible: false,
                uploadList: this.imgList
                // [
                //     {
                //         'name': 'a42bdcc1178e62b4694c830f028db5c0',
                //         'url': 'https://o5wwk8baw.qnssl.com/a42bdcc1178e62b4694c830f028db5c0/avatar',
                //         'status': 'finished',
                //         'showProgress': false,
                //         'percentage': 100
                //     }
                // ]
            };
        },
        methods: {
            changeInputFile () {
                let _this = this;
                console.log(this.$refs.input_file.files[0]);
                let file = this.$refs.input_file.files[0];
                console.log('file==>', file);
                let reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = function (e) {
                    let result = this.result;
                    console.log('e -->', e);

                    let uploadLength = 1024 * 500; // 每次传多少KB
                    let timestamp = new Date().getTime();
                    let startIndex = result.indexOf(',') + 1; // 查找数据中逗号以后第一位开始查找

                    result = result.slice(startIndex, result.length); // 查找并截取
                    let imgSize = result.length; // 文件的大小
                    let forNum = Math.ceil(imgSize / uploadLength); // 需要切割多少次
                    console.log('总共切多少次', forNum);
                    // console.log('截取完毕', result);
                    // 分片传输图片文件，每次传输1MB大小
                    _this.uploadList.push({
                        'url': '',
                        'status': '',
                        'showProgress': true,
                        'percentage': 10
                    });
                    for (let i = 0; i < forNum; i++) {
                        let isStopFlag = false; // 最后一次标识
                        if (forNum - 1 === i) {
                            isStopFlag = true;
                        }
                        console.log(forNum);
                        let startNum = i * uploadLength; // 切片开始位置
                        // console.log('开始位置', startNum);
                        let stopNum = startNum + uploadLength; // 切片结束位置

                        if (isStopFlag) {
                            stopNum = imgSize;
                        }
                        // console.log('结束位置', stopNum);
                        let imgData = result.slice(startNum, stopNum);
                        // console.log('切片--》', startNum, stopNum, imgData.length);

                        let postData = {
                            'img_name': file.name,
                            'img_data': imgData,
                            'timestamp': timestamp,
                            'chunk': i,
                            'img_source': 'user_avatar'
                        };
                        // console.log('imgData -->', imgData);
                        util.ajax.post('/api/img_upload', qs.stringify(postData)).then(resp => {
                            console.log('上传切片成功');
                            if (isStopFlag) {
                                console.log('最后一次');
                                setTimeout(function () {
                                    _this.heBingImg(file, timestamp, forNum);
                                    console.log('最后');
                                }, 2000);
                            }
                        });

                        if (!isStopFlag) {
                            let jindu = parseInt((i + 1) / forNum * 100);
                            console.log('jindu -->', jindu);
                            _this.uploadList[_this.uploadList.length - 1].percentage = jindu;
                        }
                        startNum = stopNum;
                    }
                };
            },
            heBingImg (file, timestamp, forNum) {
                let _this = this;
                _this.avatar = [];
                // 发起合并请求
                let postData = {
                    'img_name': file.name,
                    'timestamp': timestamp,
                    'chunk_num': forNum,
                    'picture_type': 1,
                    'img_source': 'user_avatar'
                };
                util.ajax.post('/api/img_merge', qs.stringify(postData)).then(resp => {
                    console.log('resp -->', resp);
                    if (resp.data.code === 200) {
                        console.log('合并切片成功');
                        console.log(resp.data.data.picture_url);
                        let item = _this.uploadList[_this.uploadList.length - 1];
                        item.percentage = 100;
                        item.showProgress = false;
                        item.status = 'finished';
                        item.url = resp.data.data.picture_url;
                        console.log('_this.uploadList --> ', _this.uploadList);
                    }
                }).catch(resp => {
                    console.log('合并切片请求失败');
                });
            },
            uploadImg () {
                this.$refs.input_file.click();
            },
            handleView (imgUrl) {
                this.imgUrl = this.ajaxUrl + '/' + imgUrl;
                this.visible = true;
            },
            handleRemove (file) {
                this.uploadList.splice(this.uploadList.indexOf(file), 1);
            },
            // handleSuccess (res, file) {
            //     file.url = 'https://o5wwk8baw.qnssl.com/7eb99afb9d5f317c912f08b5212fd69a/avatar';
            //     file.name = '7eb99afb9d5f317c912f08b5212fd69a';
            // },
            // handleFormatError (file) {
            //     this.$Notice.warning({
            //         title: 'The file format is incorrect',
            //         desc: 'File format of ' + file.name + ' is incorrect, please select jpg or png.'
            //     });
            // },
            // handleMaxSize (file) {
            //     this.$Notice.warning({
            //         title: 'Exceeding file size limit',
            //         desc: 'File  ' + file.name + ' is too large, no more than 2M.'
            //     });
            // },
            // handleBeforeUpload () {
            //     const check = this.uploadList.length < 5;
            //     if (!check) {
            //         this.$Notice.warning({
            //             title: 'Up to five pictures can be uploaded.'
            //         });
            //     }
            //     return check;
            // }
        },
        mounted () {}
    };
</script>
<style>
    .demo-upload-list{
        display: inline-block;
        width: 60px;
        height: 60px;
        text-align: center;
        line-height: 60px;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0,0,0,.2);
        margin-right: 4px;
    }
    .demo-upload-list img{
        width: 100%;
        height: 100%;
    }
    .demo-upload-list-cover{
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0,0,0,.6);
    }
    .demo-upload-list:hover .demo-upload-list-cover{
        display: block;
    }
    .demo-upload-list-cover i{
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }

    .ivu-modal-wrap-custom {
        z-index: 1001;
    }
</style>
